import * as React from 'react'
import { FormEvent, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Capsule } from '../Capsule/Capsule'
import style from './style.module.less'
import axios from 'axios'
import { store } from '../../mobx/Store'
import { Observer } from 'mobx-react'

function Put() {
  const [nameState, setNameState] = useState<string>('')
  const [mailState, setMailState] = useState<string>('')
  const [timeState, setTimeState] = useState<string>('')
  const [contentState, setContentState] = useState<string>('')
  const [tipsState, setTipsState] = useState<string>('')

  const [nameIf, setNameIf] = useState<boolean>(false)
  const [mailIf, setMailIf] = useState<boolean>(false)
  const [mailCheckIf, setMailCheckIf] = useState<boolean>(false)
  const [contentIf, setContentIf] = useState<boolean>(false)

  useEffect(() => {
    //挂载时调用
    setTimeState(getNowDate())
  }, [])

  const fetchData = async (date: Capsule) => {
    try {
      let response = await axios.post('/api/add', JSON.stringify(date))
      if (response.data.stat === 'ok') {
        console.log(response.data.id)
        //函数组件中的路由跳转
        window.location.href = `/put_done/${response.data.id}`
      }
    } catch (error) {
      console.log(error)
    }
  }

  async function put(e: FormEvent) {
    if (
      nameState !== '' &&
      mailState !== '' &&
      timeState !== '' &&
      contentState !== '' &&
      checkMail(mailState)
    ) {
      let date: Capsule = {
        name: nameState,
        email: mailState,
        time: timeState,
        content: contentState,
        tip: tipsState,
      }
      await fetchData(date)
    } else {
      inputError()
    }
  }

  function inputError() {
    if (nameState === '') setNameIf(true)
    else setNameIf(false)
    if (mailState === '') setMailIf(true)
    else setMailIf(false)
    if (contentState === '') setContentIf(true)
    else setContentIf(false)
    if (!checkMail(mailState)) setMailCheckIf(true)
    else setMailCheckIf(false)
  }

  function checkMail(str: string) {
    let Expression = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/
    if (Expression.test(str)) {
      return true
    } else {
      return false
    }
  }

  function getNowDate() {
    const date = new Date()
    let month: string | number = date.getMonth() + 1
    let strDate: string | number = date.getDate()
    let hour: string | number = date.getHours()
    let min: string | number = date.getMinutes()
    let sec: string | number = date.getSeconds()

    if (month <= 9) {
      month = '0' + month
    }

    if (strDate <= 9) {
      strDate = '0' + strDate
    }

    if (hour <= 9) hour = '0' + hour

    if (min <= 9) min = '0' + min

    if (sec <= 9) sec = '0' + sec

    return (
      date.getFullYear() +
      '-' +
      month +
      '-' +
      strDate +
      ' ' +
      hour +
      ':' +
      min +
      ':' +
      sec
    )
  }

  return (
    <div>
      <header className={style.top}>
        <div className={style.top_main}>
          <Link className={style.top_img} to="/">
            时间胶囊
          </Link>
          <div>
            <Link className={style.top_back} to="/">
              首页
            </Link>
            <Link className={style.top_put} to="/put">
              添加
            </Link>
            <Link className={style.top_open} to="/open">
              打开
            </Link>
          </div>
          <div className={style.changColor} onClick={() => store.setClick()}>
            更换主题
          </div>
        </div>
      </header>
      <main className={style.bottom}>
        <div className={style.container}>
          <h1 className={style.page_header}>添加胶囊</h1>
          <div className={style.main}>
            <form name="form" className={style.form}>
              <label>你的名字</label>
              {nameIf ? (
                <div className={style.err_name}>名字 必须填写.</div>
              ) : (
                <></>
              )}
              <input
                className={style.name}
                value={nameState}
                onChange={(e) => setNameState(e.target.value)}
                type="text"
              />
              <label>你的邮箱</label>
              {mailIf ? (
                <div className={style.err_mail}>邮箱 必须填写.</div>
              ) : (
                <></>
              )}
              {!mailIf && mailCheckIf ? (
                <div className={style.err_mail}>
                  邮箱 必须是一个有效的电子邮箱地址.
                </div>
              ) : (
                <></>
              )}
              <input
                className={style.e_mail}
                value={mailState}
                onChange={(e) => setMailState(e.target.value)}
                type="text"
              />
              <label>打开时间</label>
              <input
                className={style.time}
                value={timeState}
                onChange={(e) => setTimeState(e.target.value)}
                type="text"
              />
              <span className={style.tips}>
                打开时间之前，胶囊内容是看不到的。
              </span>
              <label>胶囊内容</label>
              {contentIf ? (
                <div className={style.err_nr}>内容 必须填写.</div>
              ) : (
                <></>
              )}
              <textarea
                className={style.neirong}
                value={contentState}
                onChange={(e) => setContentState(e.target.value)}
                rows={8}
                cols={50}
              />
              <span className={style.tips}>胶囊内容不能超过5000字。</span>
              <label className={style.tips_label}>未到期提示信息</label>
              <textarea
                className={style.tip}
                value={tipsState}
                onChange={(e) => setTipsState(e.target.value)}
                rows={3}
                cols={50}
              />
              <span className={style.tips}>
                在 打开时间 之前打开胶囊，会看到提示信息。
              </span>
              <p className={style.add}>
                {/*{localStore.click ? <input type="button" className={style.formButton} onClick={(e)=>{put(e)}} value="添加胶囊"/>*/}
                {/*: <input type="button" className={style.formButtonChange} onClick={(e)=>{put(e)}} value="添加胶囊"/>}*/}
                <Observer>
                  {() => (
                    <>
                      {store.click ? (
                        <input
                          type="button"
                          className={style.formButton}
                          onClick={(e) => {
                            put(e)
                          }}
                          value="添加胶囊"
                        />
                      ) : (
                        <input
                          type="button"
                          className={style.formButtonChange}
                          onClick={(e) => {
                            put(e)
                          }}
                          value="添加胶囊"
                        />
                      )}
                    </>
                  )}
                </Observer>
              </p>
            </form>
          </div>
        </div>
      </main>
    </div>
  )
}

export default Put
